package test4;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Consumer {
    public static void main(String[] args) {

        Queue<String> queue = new ArrayDeque<>(3);
        ReentrantLock reentrantLock = new ReentrantLock();
        Condition fullcondition = reentrantLock.newCondition();
        Condition emptycondition = reentrantLock.newCondition();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                reentrantLock.lock();
                try {
                    while (queue.size() == 3) {
                        emptycondition.await();
                    }
                    queue.add("面包");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(3));
                    System.out.println(Thread.currentThread().getName() + "生产了一个面包");
                    fullcondition.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    reentrantLock.unlock();
                }
            }

        }, "面包师").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                reentrantLock.lock();
                try {
                    while (queue.isEmpty()) {
                        fullcondition.await();
                    }
                    queue.remove();
                    TimeUnit.SECONDS.sleep(new Random().nextInt(3));
                    System.out.println(Thread.currentThread().getName() + "试吃了一个面包");
                    emptycondition.signal();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    reentrantLock.unlock();
                }
            }
        }, "试吃员").start();
    }
}
